//
//  ONMessageViewController.m
//  XProject
//
//  Created by Familly on 3/5/15.
//  Copyright (c) 2015 Familly. All rights reserved.
//

#import "ONMessageViewController.h"
#import "ONMessageTableViewCell.h"
#import "ONSettingViewController.h"
#import "ONReportViewController.h"
#import "ONGetDataRequestEntity.h"
#import "ONGetDataResponseEntity.h"
#import "ONMessageEntity.h"
#import "ONLoginFetcher.h"
#import <SDWebImage/UIImageView+WebCache.h>
@interface ONMessageViewController ()

@end

@implementation ONMessageViewController
@synthesize dataArray=_dataArray;


+ (instancetype)sharedInstance {
    static id messageVCSharedInstance = nil;
    static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
        messageVCSharedInstance = [[self alloc] initFromIB];
    });
    return messageVCSharedInstance;
}
-(id)initFromIB{
    UIStoryboard *iPhoneStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    self = [iPhoneStoryboard instantiateViewControllerWithIdentifier:@"ONMessageViewController"];
    self.view.frame = APP_DELEGATE.window.bounds;
   // self.view.hidden = YES;
    [APP_DELEGATE.window addSubview:self.view];
    [APP_DELEGATE.window sendSubviewToBack:self.view];
    
    if (self) {
        
    }
    
    return self;
}
-(void)setDataArray:(NSMutableArray *)array
{
    _dataArray=array;
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _tableView.delegate=self;
    _tableView.dataSource=self;
    [_lbMessage setTextColor:TEXT_TITLE_COLOR];
   
    _dataArray=[ONGlobal getMessageArray];
     [_tableView reloadData];
    //NSLog(@"count %d",[_dataArray count]);
    
}
-(void)dealloc
{
    _tableView.delegate=nil;
    _tableView.dataSource=nil;
}
- (IBAction)settingClick:(id)sender {

    for (UIViewController *viewC in self.navigationController.viewControllers) {
        if ([viewC isKindOfClass:[ONSettingViewController class]]) {
            
            [self.navigationController popToViewController:viewC animated:NO];
            return;
        }
    }
    [self.navigationController pushViewController:[ONSettingViewController sharedInstance] animated:false];
}
- (IBAction)reportClick:(id)sender {
    for (UIViewController *viewC in self.navigationController.viewControllers) {
        if ([viewC isKindOfClass:[ONReportViewController class]]) {
           [self.navigationController popToViewController:viewC animated:NO];
            return;
        }
    }
    [[ONReportViewController sharedInstance] initUI];
    [self.navigationController pushViewController:[ONReportViewController sharedInstance] animated:false];
}

#pragma mark - UITableViewDataSource Methods
 -(CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {return 100;}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger numberOfCell = [_dataArray count];
    return numberOfCell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
        NSString *reuseIdentifier = @"ONMessageTableViewCell";
        ONMessageTableViewCell *cell = (ONMessageTableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (!cell) {
            cell = (ONMessageTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:reuseIdentifier owner:self options:nil] objectAtIndex:0];
        }
    ONMessageEntity *item =[_dataArray objectAtIndex:indexPath.row];
    cell.text1.text=item.username;
    cell.text2.text=item.date_comment;
    cell.textView.text =item.description;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // download logo
        NSURL *url_logo = [NSURL URLWithString:item.image];
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        SDWebImageOptions option=SDWebImageRetryFailed;
        [manager downloadWithURL:url_logo options:option progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            ///
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {
            cell.imageIcon.image=image;
            [cell.indicatior stopAnimating];
            [cell.indicatior setHidden:TRUE];
            
        }];
    });
    
    return cell;
}

#pragma mark - UITableViewDelegate Methods
- (UITableViewCell *)getLoadingCellForTableView:(UITableView *)tableView {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    
    // Create a cell with active indicator
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        
        // Add loading indicator
        UIActivityIndicatorView *loadingIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, cell.contentView.frame.size.width, cell.contentView.frame.size.height)];
        loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        loadingIndicator.tag = 2000;
        loadingIndicator.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [cell.contentView addSubview:loadingIndicator];
    }
    
    // Start loadingIndicator
    UIActivityIndicatorView *loadingIndicator = (UIActivityIndicatorView *)[cell viewWithTag:2000];
    [loadingIndicator startAnimating];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // Deselect the row
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - EGORefreshTableHeaderDelegate Methods
- (void)startPullDownRefresh {
    // Add Pull Down Refresh view
    if (_refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
		view.delegate = self;
		[self.tableView addSubview:view];
		_refreshHeaderView = view;
	}
    
    //  update the last update date
    [_refreshHeaderView refreshLastUpdatedDate];
    
    // manual trigger loading
    [_refreshHeaderView egoRefreshScrollViewDataSourceStartManualLoading:self.tableView];
}

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view {
    [self requestGetData];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view {
	
	return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view {
	
	return [NSDate date]; // should return date data source was last changed
}

#pragma mark - Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource {
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
}

- (void)doneLoadingTableViewData {
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
}
#pragma mark - REQUEST GET DATA
- (void)requestGetData {
    
}

@end
